package controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import repository.UserRepository;
import util.ApiClientBuilder;
import util.FacebookMatchHelper;
import util.LinkedInMatchHelper;

import com.google.code.linkedinapi.client.LinkedInApiClientException;

import domain.User;

@Service 
public class ServerScanner 
{    
	@Autowired
	private UserRepository userRepository;
	@Autowired
	@Qualifier("linkedInMatchHelperJob")
	private LinkedInMatchHelper linkedInMatchHelper;
	
	@Autowired
	@Qualifier("facebookMatchHelperJob")
	private FacebookMatchHelper facebookMatchHelper;
	
	@Scheduled(cron = " 0 0 0 * * 1")
	protected void executeInternal(){
		System.out.println("ENTRE AL CRON!!");
		  List<User> users = userRepository.getRegularConfirmedUsers();
		  User adminSocialUser = userRepository.getAdminUserWithSocialToken();
		  final String LINKEDIN_API_KEY = "rnaeme79uqz5";
		  final String LINKEDIN_API_SECRET = "nz5A3kPcwP0yzkfs";
		  final String FACEBOOK_API_KEY = "429147717173757";
		  final String FACEBOOK_API_SECRET = "3d822d5a2feda7a4dc390cb3e0ced38f";

		  if (adminSocialUser != null) {
		  
			  ApiClientBuilder apiClientBuilder = new ApiClientBuilder();
	
			  System.out.println("Starting linkedin match!!");
			  
			  if (apiClientBuilder.buildLinkedInApiClient(adminSocialUser,
					  LINKEDIN_API_KEY, LINKEDIN_API_SECRET)) {
			  	try {
		  			linkedInMatchHelper.match(apiClientBuilder, users);
			  	} catch (LinkedInApiClientException e) {
			  	}	
			  }
			  
			  System.out.println("Starting facebook match!!");
			  
			  if (apiClientBuilder.buildFacebookClient(adminSocialUser, FACEBOOK_API_KEY, FACEBOOK_API_SECRET)) {
				  try {
			  			facebookMatchHelper.match(apiClientBuilder, users);
				  	} catch (Exception e) {
				  	}  
			  }
			  System.out.println("Match END!!");
			  
			  if (users != null) {
				  for (User u : users) {
					  userRepository.updateUser(u);
				  }
			  }
		  }
		  
	}
}
